package wang.chunfan.mybatis.exception;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import wang.chunfan.mybatis.log.LogProducer;
import wang.chunfan.mybatis.pojo.ErrorLog;
import wang.chunfan.mybatis.tool.ExceptionUtils;
import wang.chunfan.mybatis.tool.MessageUtils;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class MyExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyException.class);

    @Autowired
    private LogProducer logProducer;

    @ExceptionHandler(MyException.class)
    public String handleMyException(MyException ex) {
        // 自定义异常，直接抛出，向前端显示
        Map map = new HashMap(2);
        map.put("msg", ex.getMsg());
        map.put("code", ex.getCode());
        return JSON.toJSONString(map);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public String handleDuplicateKeyEception(DuplicateKeyException ex) {
        // 主键冲突异常
        return MessageUtils.getMessage(10002);
    }

    @ExceptionHandler(Exception.class)
    public String handleException(Exception ex) {
        // 非预期异常，写入如 log 文件 + 写入数据库
        LOGGER.error(ex.getMessage(), ex);
        saveLog(ex);

        return MessageUtils.getMessage(500);
    }

    private void saveLog(Exception exception) {
        ErrorLog errorLog = new ErrorLog();
        // 获取异常堆栈信息
        errorLog.setErrorInfo(ExceptionUtils.getErrorStackTrace(exception));
        logProducer.saveLog(errorLog);
    }

}
